package com.viewhigh.wechat.sdk.api;

import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.sword.lang.HttpUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.viewhigh.framework.common.log.LogUtils;
import com.viewhigh.wechat.sdk.base.BaseApi;
import com.viewhigh.wechat.sdk.user.UserInfo;

/**
 * 
 * @ClassName: UserInfoUtil
 * @Description: 用户信息管理
 * @author liusongqing
 * @date 2016年4月29日 上午9:35:57
 *
 */
public class UserInfoApi extends BaseApi{

    private static final String USRE_GET_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";
    private static final String USRE_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
    private static String nextOpenId;
    private static long total = 0;

    /**
     * 调用之后的nextOpenId
     * 
     * @return 下一个开始的openid
     */
    public static String getNextOpenId() {
        return UserInfoApi.nextOpenId;
    }

    /**
     * 关注者总数,必须先调用一下subscriberList方法才能得到total
     * 
     * @return 关注者总数
     */
    public static long getTotal() {
        return UserInfoApi.total;
    }

    
    /**
     * 获取帐号的关注者列表 https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
     * 
     * @return List<String> openid 的列表
     */
    public static List<Object> subscriberList(String nextOpenId,String appId) {
        String url = USRE_GET_URL + getAccessTokenStr(appId);
        if (StringUtils.isNotBlank(nextOpenId)) {
            url += "&next_openid=" + nextOpenId;
        }
        String result = HttpUtils.get(url);
        if (StringUtils.isBlank(result))
            return null;
        return parseUserResult(result);
    }

    /**
     * 成功 {"total":2,"count":2,"data":{"openid":["","OPENID1","OPENID2"]},"next_openid":"NEXT_OPENID"}
     * 失败{"errcode":40013,"errmsg":"invalid appid"}
     * 
     * @param result
     * @return
     */
    private static List<Object> parseUserResult(String result) {
        JSONObject json = JSONObject.parseObject(result);
        // 获取错误
        if (json.containsKey("errcode")) {
            LogUtils.error("获取帐号的关注者列表错误:" + json.getString("errmsg"));
            return null;
        }
        // 获取成功
        nextOpenId = json.getString("next_openid");
        // 第一次设置total，每次的total都一样
        if (total == 0) {
            total = Long.valueOf(json.getString("total"));
        }
        JSONArray list = json.getJSONObject("data").getJSONArray("openid");
        LogUtils.debugLog("获取帐号的关注者列表成功:本次获取" + list.size());
        return list;
    }
    
    /**
     * 
     * @Title: getUserInfo @Description: 获取用户信息 @param @param openid @param @return 设定文件 @return UserInfo 返回类型 @throws
     */
    @SuppressWarnings("finally")
    public static UserInfo getUserInfo(String openid,String appId) {
        String url = USRE_INFO_URL + getAccessTokenStr(appId);
        if (StringUtils.isNotBlank(openid)) {
            url += "&openid=" + openid;
            url += "&lang=zh_CN";
        }
        HttpMethod method = new PostMethod(url);
        HttpClient httpclient = new HttpClient();
        String result = "";
        try {
            httpclient.executeMethod(method);
            result = new String(method.getResponseBody(), "utf-8");
        } catch (Exception e1) {
            e1.printStackTrace();
            LogUtils.error("获取个人信息异常:" + e1.getMessage(), e1);
        } finally {
            if (StringUtils.isBlank(result))
                return null;
            return parseUserInfoResult(result);
        }
    }

    /**
     * 
     * @Title: parseUserInfoResult 成功返回： { "subscribe": 1, "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", "nickname": "Band",
     *         "sex": 1, "language": "zh_CN", "city": "广州", "province": "广东", "country": "中国", "headimgurl":
     *         "http://wx.qlogo.cn/mmopen/
     *         g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0
     *         ", "subscribe_time": 1382694957, "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL" "remark": "", "groupid": 0 }
     *         失败返回：{"errcode":40013,"errmsg":"invalid appid"} @param @param result @param @return 设定文件 @return UserInfo
     *         返回类型 @throws
     */
    private static UserInfo parseUserInfoResult(String result) {
        JSONObject json = JSONObject.parseObject(result);
        // 获取错误
        if (json.containsKey("errcode")) {
            LogUtils.error("获取用户个人信息错误:" + json.getString("errmsg"));
            return null;
        }
        UserInfo user = JSONObject.parseObject(result, UserInfo.class);
        // 获取成功
        String openid = json.getString("openid");
        LogUtils.debugLog("获取用户个人信息成功！openid=" + openid);
        return user;
    }
}
